<template>
  <div class="run-modal-style">
    <Form
      :model="modelForm"
      ref="editForm"
      class="ivu-form-no-margin-bottom"
      :rules="rule"
      :label-width="100"
    >
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="postCode" :label="$t('module.post.postCode')">
            <Input
              placeholder
              v-model="modelForm.postCode"
              :maxlength="50"
              :disabled="postId != ''"
              
              style="width: 100%;"
            ></Input>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="postName" :label="$t('module.post.postName')">
            <Input
              placeholder
              v-model="modelForm.postName"
              :maxlength="50"
              
              style="width: 100%;"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="effectBegin" :label="$t('module.post.effectBegin')">
            <DatePicker
              type="date"
              ref="effectBegin"
              :placeholder="$t('module.role.selectDate')"
              :value="modelForm.effectBegin"
              
              @on-change="changeEffectBegin"
              @on-clear="clearEffectBegin"
              style="width: 100%;"
            ></DatePicker>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="effectEnd" :label="$t('module.post.effectEnd')">
            <DatePicker
              type="date"
              ref="effectEnd"
              :placeholder="$t('module.role.selectDate')"
              :value="modelForm.effectEnd"
              
              @on-change="changeEffectEnd"
              @on-clear="clearEffectEnd"
              style="width: 100%;"
            ></DatePicker>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="productId" :label="$t('module.valueSet.ownnerproduct')">
            <Select
              v-model="modelForm.productId"
              style="width:100%"
              
              :disabled="adminProductId!='' || postId != ''"
              clearable
            >
              <Option
                v-for="product in productList"
                :value="product.vsiKey"
                :key="product.vsiKey"
              >{{product.vsiValue}}</Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="tenantCode" :label="$t('module.post.tenantCode')">
            <Select
              v-model="modelForm.tenantCode"
              style="width:100%"
              
              :disabled="tenantCode!=null || postId != ''"
              clearable
              :transfer="true"
            >
              <Option
                v-for="tenant in tenantList"
                :value="tenant.tenantCode"
                :key="tenant.tenantCode"
              >{{tenant.tenantName}}</Option>
            </Select>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" style="width: 100%;" size="small">
              <Radio :label="1">
                <span>启用</span>
              </Radio>
              <Radio :label="0">
                <span>停用</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;" v-if="isShowOrg">
          <Form-item prop="orgId" :label="$t('module.post.orgName')">
            <Select-Org
              :rootOrgId="rootOrgId"
              :rootOrgName="rootOrgName"
              :orgName="modelForm.treeNodeName"
              v-model="modelForm.treeNodeId"
              style="width: 100%;"
              
            />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="24" style="border:none;">
          <!-- 备注 改为 描述 -->
          <Form-item :label="$t('common.describe')">
            <Input
              placeholder
              type="textarea"
              :rows="4"
              v-model="modelForm.remark"
              :maxlength="200"
              style="width: 100%;"
              
            ></Input>
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
import { getPostDetail, updatePost, addPost } from "@/api/postApi.js";
import valueSetAPI from "@/api/valueSetAPI.js";
import tenantAPI from "@/api/tenantApi.js";
import locales from "./locales.js";
import SelectOrg from "@/components/SelectOrg/SelectOrg.vue";

export default {
  name: "postedit",
  mixins: [locales],
  components: {
    SelectOrg
  },
  props: {
    postId: {
      type: String,
      default: ""
    },
    adminProductId: {
      type: String,
      default: null
    },
    tenantCode: {
      type: String,
      default: null
    },
    rootOrgId: {
      type: String,
      default: null
    },
    rootOrgName: {
      type: String,
      default: null
    }
  },
  data() {
    const validatePostCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.post.warning.enterPostCode")));
      } else if (value.length > 50) {
        callback(new Error(this.$t("module.post.warning.maxFifty")));
      } else if (!new RegExp("^([a-zA-z0-9]|_|-)+$").test(value)) {
        callback(new Error(this.$t("module.post.warning.codeFormat")));
      }
      callback();
    };

    return {
      modelForm: {
        id: this.postId,
        productId: "",
        tenantCode: this.tenantCode,
        treeNodeId: null,
        treeNodeName: null,
        postCode: "",
        postName: "",
        effectBegin: "",
        effectEnd: "",
        remark: "",
        enabled: 1
      },
      rule: {
        postCode: [{ validator: validatePostCode, trigger: "blur", required: true }],
        postName: [
          {
            required: true,
            message: this.$t("module.post.warning.enterPostName"),
            trigger: "blur"
          }
        ]
      },
      productList: [],
      tenantList: [],
      isShowOrg: false
    };
  },
  computed: {
    actions() {
      return [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          theme: "primary",
          handle: () => {
            this.$emit("Close");
          }
        }
      ];
    }
  },
  created() {
    if (this.postId) {
      this.$emit("SetTitle", this.$t("module.post.editPost"));
    } else {
      this.$emit("SetTitle", this.$t("module.post.createPost"));
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
    this.init();
  },
  methods: {
    init() {
      if (this.postId) {
        getPostDetail(this.postId).then(response => {
          this.modelForm = response.data;
          // 有配置时，加载到数据再回显
          this.isShowOrg = !!window.RPConfig.orgTreeCode;
        });
      } else {
        // 默认有效期
        var date = new Date();
        var month = date.getMonth() + 1;
        var currentDate = date.getFullYear() + "-" + month + "-" + date.getDate();
        var endDate = date.getFullYear() + 50 + "-" + month + "-" + date.getDate();

        this.modelForm.effectBegin = currentDate;
        this.modelForm.effectEnd = endDate;
        // 有配置才显示
        this.isShowOrg = !!window.RPConfig.orgTreeCode;
      }
      this.initProduct();
      this.initTenant();
    },
    // 初始化所属产品
    initProduct() {
      valueSetAPI.getValueSetByCode("RC_PRODUCT").then(data => {
        this.productList = data;
      });
      // 新增岗位时
      if (this.postId == "") {
        if (this.adminProductId != "") {
          // 为产品管理员、应用管理员时
          this.modelForm.productId = this.adminProductId;
        }
      }
    },
    // 初始化所属租户
    initTenant() {
      if (this.postId) {
        tenantAPI.queryAllTenantList().then(data => {
          this.tenantList = data;
        });
      } else {
        tenantAPI.queryTenantList().then(data => {
          this.tenantList = data;
        });
      }
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (this.modelForm.id) {
            updatePost(this.modelForm)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: "编辑岗位成功",
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          } else {
            addPost(this.modelForm)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: "新增岗位成功",
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          }
        } else {
          this.$message.error({
            content: this.$t("module.valueSet.formValidateFailed"),
            duration: 3
          });
        }
      });
    },
    changeEffectBegin(date) {
      if (this.modelForm.effectEnd && date && new Date(date) > new Date(this.modelForm.effectEnd)) {
        this.modelForm.effectBegin = "";
        this.$refs["effectBegin"].handleClear();
        this.$message.error({
          content: this.$t("module.valueSet.warning.dateCompare")
        });
        return;
      }

      this.modelForm.effectBegin = date;
    },
    clearEffectBegin() {
      this.modelForm.effectBegin = "";
    },
    changeEffectEnd(date) {
      if (this.modelForm.effectBegin && date && new Date(date) < new Date(this.modelForm.effectBegin)) {
        this.modelForm.effectEnd = "";
        this.$refs["effectEnd"].handleClear();
        this.$message.error({
          content: this.$t("module.valueSet.warning.dateCompare")
        });
        return;
      }

      this.modelForm.effectEnd = date;
    },
    clearEffectEnd() {
      this.modelForm.effectEnd = "";
    }
  },
  watch: {},
  directives: {}
};
</script>
